<template>
  <div class="payment-start-scan">
    <div class="scan-container">
      <div class="scan-card">
        <div class="scan-icon">
          <el-icon><Camera /></el-icon>
        </div>

        <h3 class="scan-title">请扫描医保卡/电子医保凭证</h3>
        <p class="scan-desc">将医保卡条形码或电子医保二维码对准扫描区域</p>

        <div class="scan-area">
          <div class="scan-frame">
            <div class="scan-animation"></div>
            <div class="scan-text">
              <el-icon class="scan-icon"><Camera /></el-icon>
              <steambarcodereader v-show="false" ref="barcodeReaderRef" @decode="startCameraScan" />
            </div>
          </div>
        </div>

        <div class="scan-tips">
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>请将医保卡条形码或手机上的电子医保二维码对准上方扫描框</span>
          </div>
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>保持卡片平整，距离扫描器约10-15厘米</span>
          </div>
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>光线充足时扫码效果更佳</span>
          </div>
        </div>

        <div class="action-buttons">
          <el-button
            class="manual-input-btn"
            type="primary"
            plain
            @click="handleManualInput"
          >
            <el-icon><Edit /></el-icon>
            手动输入卡号
          </el-button>

          <el-button
            class="test-scan-btn"
            type="primary"
            @click="handleTestScan"
          >
            <el-icon><Camera /></el-icon>
            模拟扫码（测试）
          </el-button>
        </div>
      </div>
    </div>

    <!-- 手动输入对话框 -->
    <el-dialog
      v-model="showManualDialog"
      title="手动输入医保卡号"
      width="400px"
      center
    >
      <div class="manual-input-dialog">
        <el-form :model="manualForm" :rules="manualRules" ref="manualFormRef">
          <el-form-item label="医保卡号" prop="cardNumber">
            <el-input
              v-model="manualForm.cardNumber"
              placeholder="请输入医保卡号"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
        </el-form>

        <div class="dialog-tips">
          <el-icon><InfoFilled /></el-icon>
          <span>请输入医保卡正面的18位卡号</span>
        </div>
      </div>

      <template #footer>
        <el-button @click="showManualDialog = false">取消</el-button>
        <el-button type="primary" @click="handleManualConfirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive,onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
// 引入二维码扫码组件
import steambarcodereader from "@/components/qrcode/steambarcodereader.vue";
// 引入API
import { queryQrCode } from "@/api/api";

const router = useRouter();
const showManualDialog = ref(false);
const manualFormRef = ref();
// 添加扫码组件的 ref
const barcodeReaderRef = ref(null)

// 手动输入表单
const manualForm = reactive({
  cardNumber: "",
});

// 表单验证规则
const manualRules = {
  cardNumber: [
    { required: true, message: "请输入医保卡号", trigger: "blur" },
    { min: 16, max: 20, message: "医保卡号长度在16-20位之间", trigger: "blur" },
  ],
};

// 处理手动输入
const handleManualInput = () => {
  showManualDialog.value = true;
};

// 手动输入确认
const handleManualConfirm = async () => {
  if (!manualFormRef.value) return;

  try {
    await manualFormRef.value.validate();

    const params = { insurance_card_number: manualForm.cardNumber };

    const response = await queryQrCode(params);
    console.log("手动输入获取患者信息响应:", response);

    if (response && response.code == 200) {
      const preload = response.data;
      const patientInfo = {
        insurance_id: preload.insurance_id,
        cardNumber: preload.insurance_card_number,
        name: preload.patient_name,
        idNumber: preload.id_number,
        phone: preload.phone_number,
        insuranceType: preload.insurance_type,
        reimbursement_rate: preload.reimbursement_rate,
      };

      localStorage.setItem("currentPatient", JSON.stringify(patientInfo));
      ElMessage.success(`欢迎 ${patientInfo.name} 就诊`);

      // 关闭摄像头（如果是真实扫码）
      if (barcodeReaderRef.value && barcodeReaderRef.value.stopCamera) {
        barcodeReaderRef.value.stopCamera();
      }

      // 跳转到挂号父组件选择页面
      router.push("/self-service/registration-selection");
    }else {
      ElMessage.error(response.message || "未找到对应的患者信息");
    }
  } catch (error) {
    ElMessage.error("请输入有效的医保卡号");
  }
};

// 模拟扫码（测试用）
const handleTestScan = async () => {
  ElMessage.success("扫码成功，正在获取患者信息...");

  const params = { qr_code_data: "TIANJIN_6023425_WANGFANG" };

  const response = await queryQrCode(params);

  console.log("模拟扫码获取患者信息响应:", response);

  if (response && response.code == 200) {
    const preload = response.data;
    const patientInfo = {
      insurance_id: preload.insurance_id,
      cardNumber: preload.insurance_card_number,
      name: preload.patient_name,
      idNumber: preload.id_number,
      phone: preload.phone_number,
      insuranceType: preload.insurance_type,
      reimbursement_rate: preload.reimbursement_rate,
    };

    localStorage.setItem("currentPatient", JSON.stringify(patientInfo));
    ElMessage.success(`欢迎 ${patientInfo.name} 就诊`);

    // 关闭摄像头（如果是真实扫码）
    if (barcodeReaderRef.value && barcodeReaderRef.value.stopCamera) {
      barcodeReaderRef.value.stopCamera();
    }

    // 跳转到挂号父组件选择页面
    router.push("/self-service/registration-selection");
  }
};

// 实际项目中这里应该集成真实的扫码功能
const startCameraScan = (txt) => {
  // 调用摄像头扫码API
  getPatientInfoByQRCode(txt);
  // 扫码成功后关闭摄像头
  if (barcodeReaderRef.value && barcodeReaderRef.value.stopCamera) {
    barcodeReaderRef.value.stopCamera();
  }
};

// 请求后端根据扫描的二维码数据获取当前患者的基础信息
const getPatientInfoByQRCode = async (qrcodedata) => {
  const params = { qr_code_data: qrcodedata };

  const response = await queryQrCode(params);

  if (response && response.code == 200) {
    const preload = response.data;
    const patientInfo = {
      insurance_id: preload.insurance_id,
      cardNumber: preload.insurance_card_number,
      name: preload.patient_name,
      idNumber: preload.id_number,
      phone: preload.phone_number,
      insuranceType: preload.insurance_type,
      reimbursement_rate: preload.reimbursement_rate,
    };

    localStorage.setItem("currentPatient", JSON.stringify(patientInfo));
    ElMessage.success(`欢迎 ${patientInfo.name} 就诊`);

    // 跳转到挂号父组件选择页面
    router.push("/self-service/registration-selection");
  }
};

// 组件卸载时关闭摄像头
onUnmounted(() => {
  if (barcodeReaderRef.value && barcodeReaderRef.value.stopCamera) {
    barcodeReaderRef.value.stopCamera()
  }
})
</script>

<style lang="scss" scoped>
.payment-start-scan {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 28px;
    font-weight: 600;
  }

  .step-indicator {
    color: #909399;
    font-size: 16px;
    font-weight: 500;
  }
}

.scan-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.scan-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 100%;
  max-width: 500px;
}

.scan-icon {
  font-size: 64px;
  color: #1a75bc;
  margin-bottom: 20px;
}

.scan-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.scan-desc {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
}

.scan-area {
  margin: 30px 0;
  display: flex;
  justify-content: center;
}

.scan-frame {
  width: 250px;
  height: 150px;
  border: 3px dashed #1a75bc;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  background: #f8fafc;
}

.scan-animation {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, #1a75bc, transparent);
  animation: scan 2s linear infinite;
}

@keyframes scan {
  0% {
    top: 0;
  }
  50% {
    top: 100%;
  }
  100% {
    top: 0;
  }
}

.scan-text {
  color: #1a75bc;
  font-size: 16px;
  font-weight: 500;
  z-index: 1;
}

.scan-tips {
  background: #f0f7ff;
  border-radius: 8px;
  padding: 20px;
  margin: 30px 0;
  text-align: left;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }

  .el-icon {
    color: #1a75bc;
    margin-right: 10px;
    margin-top: 2px;
    flex-shrink: 0;
  }

  span {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
  }
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;

  .el-button {
    min-width: 160px;
    height: 44px;
    font-size: 16px;

    .el-icon {
      margin-right: 8px;
    }
  }
}

.manual-input-dialog {
  .dialog-tips {
    display: flex;
    align-items: center;
    background: #f0f7ff;
    padding: 12px;
    border-radius: 6px;
    margin-top: 15px;

    .el-icon {
      color: #1a75bc;
      margin-right: 8px;
    }

    span {
      color: #606266;
      font-size: 14px;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-start-scan {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;

    h2 {
      font-size: 24px;
    }
  }

  .scan-card {
    padding: 30px 20px;
  }

  .scan-icon {
    font-size: 48px;
  }

  .scan-title {
    font-size: 20px;
  }

  .scan-frame {
    width: 200px;
    height: 120px;
  }

  .action-buttons {
    flex-direction: column;

    .el-button {
      width: 100%;
      max-width: 280px;
    }
  }
}
</style>